package com.ssy.lingxi.search.serviceImpl;

import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.tree.Node;
import com.ssy.lingxi.common.constant.tree.TreeUtils;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.search.common.tree.CategoryNode;
import com.ssy.lingxi.search.service.IScoreService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 店铺实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class ScoreServiceImpl implements IScoreService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Resource
    private IRedisStringUtils redisStringUtils;

    /**
     * 查询商品分类树
     * @param storeId
     * @return
     */
    @Override
    public List<Node> getCategoryTree(Long shopId, Long storeId) {
        // 查询条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if(storeId != null && storeId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("storeId", storeId));
        }

        // 按商城环境
        if(shopId != null && shopId > 0){
            queryBuilder.must(QueryBuilders.matchQuery("commodityShopList.shopId", shopId));
        }
//        if(type != null && type > 0){
//            queryBuilder.must(QueryBuilders.matchQuery("commodityShopList.type", type));
//        }
//        if(environment != null && environment > 0){
//            queryBuilder.must(QueryBuilders.matchQuery("commodityShopList.environment", environment));
//        }
        //构建查询条件
        SearchRequest search = new SearchRequest(Constants.ES_COMMODITY_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(0);
        searchSourceBuilder.query(queryBuilder);
        //分组
        TermsAggregationBuilder aggregationCategoryId = AggregationBuilders.terms("group_categoryId").field("customerCategory.fullId.keyword").size(1200000);
        searchSourceBuilder.aggregation(aggregationCategoryId);
        search.source(searchSourceBuilder);
        try{
            CategoryNode categoryNode = new CategoryNode();
            //搜索
            SearchResponse searchResponse = restHighLevelClient.search(search, RequestOptions.DEFAULT);
            Aggregations aggregations = searchResponse.getAggregations();
            if(aggregations != null){
                Terms brandTerms = aggregations.get("group_categoryId");
                List<? extends Terms.Bucket> brandBuckets = brandTerms.getBuckets();
                if(brandBuckets != null){
                    brandBuckets.forEach(bucket -> {
                        //将品类进行组装
                        String fullId = String.valueOf(bucket.getKey());
                        if(fullId.contains(Constants.SPLIT_STR_FULL_ID)){
                            String[] split = fullId.split(Constants.TRANSFER_STR + Constants.SPLIT_STR_FULL_ID);
                            if(split.length > 0){
                                for(int i = 0; i < split.length; i++){
                                    if(i == 0){
                                        //一级品类
                                        Set<Long> rootList = categoryNode.getRootList() == null ? new HashSet<>() : categoryNode.getRootList();
                                        rootList.add(Long.valueOf(split[i]));
                                        categoryNode.setRootList(rootList);
                                    }
                                    //所有品类
                                    Set<Long> sourceList = categoryNode.getSourceList() == null ? new HashSet<>() : categoryNode.getSourceList();
                                    sourceList.add(Long.valueOf(split[i]));
                                    categoryNode.setSourceList(sourceList);
                                }
                            }
                        }else{
                            //商品挂在一级品类下
                            Set<Long> rootList = categoryNode.getRootList() == null ? new HashSet<>() : categoryNode.getRootList();
                            rootList.add(Long.valueOf(fullId));
                            categoryNode.setRootList(rootList);
                            //所有品类
                            Set<Long> sourceList = categoryNode.getSourceList() == null ? new HashSet<>() : categoryNode.getSourceList();
                            sourceList.add(Long.valueOf(fullId));
                            categoryNode.setSourceList(sourceList);
                        }
                    });
                }
            }
            Map<String, String> categoryMap = redisStringUtils.hGetAll(Constants.REDIS_KEY_CUSTOMER_CATEGORY, Constants.REDIS_PRODUCT_INDEX);
            Set<Long> rootCategoryIdList = categoryNode.getRootList();
            Set<Long> sourceCategoryIdList = categoryNode.getSourceList();
            //组装树结构
            if(rootCategoryIdList != null && !rootCategoryIdList.isEmpty()){
                List<Node> rootList = TreeUtils.getNodeList(rootCategoryIdList, categoryMap);
                List<Node> sourceList = TreeUtils.getNodeList(sourceCategoryIdList, categoryMap);
                return TreeUtils.buildTree(sourceList, rootList);
            }
            return new ArrayList<>();
        }catch (Exception e){
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}